from pydantic import BaseModel
from datetime import datetime
from typing import Optional, List
from passlib.context import CryptContext
import json
import os

# 强制用户数据文件存储在项目根目录（main.py所在目录）
USERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "users.json")
# 打印文件路径（启动服务时会显示）
print(f"用户数据文件路径：{USERS_FILE}")

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 用户模型
class User(BaseModel):
    id: Optional[int] = None
    username: str
    password: str  # 存储加密后的密码
    created_at: Optional[datetime] = None

class UserCreate(BaseModel):
    username: str
    password: str

class UserLogin(BaseModel):
    username: str
    password: str

# 初始化用户数据文件
def init_users_file():
    if not os.path.exists(USERS_FILE):
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False)

# 加载所有用户
def load_users() -> List[User]:
    init_users_file()
    with open(USERS_FILE, 'r', encoding='utf-8') as f:
        try:
            users_data = json.load(f)
            return [User(**item) for item in users_data]
        except json.JSONDecodeError:
            return []

# 保存用户
def save_users(users: List[User]):
    with open(USERS_FILE, 'w', encoding='utf-8') as f:
        users_dict = [user.dict() for user in users]
        json.dump(users_dict, f, ensure_ascii=False, default=str)

# 获取用户 by username
def get_user_by_username(username: str) -> Optional[User]:
    users = load_users()
    for user in users:
        if user.username == username:
            return user
    return None

# 验证密码
def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

# 密码加密
def get_password_hash(password):
    return pwd_context.hash(password)
